<!--
* @author luguoxiang
* @date 2021-09-07
* 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
-->
<template>
  <slot :text-list="textList">
    {{ textList.join(join ?? '，') }}
  </slot>
</template>

<script lang="ts" setup>
import { ref, watchEffect } from 'vue';
import { LgTextProps } from '../types';
import { getDict, toAsyncLoader } from '@/soar';

interface Props extends LgTextProps {
  /**
   * 通过接口获取
   */
  api?: string | Function;
  /**
   * 数据选项
   */
  options?: Object[] | string;
  /**
   * 值
   */
  modelValue?: Object | Object[];
  /**
   * 翻译结果连接符
   */
  join?: string;
  /**
   * 值字段
   */
  valueField?: string;
  /**
   * label字段
   */
  labelField?: string;
}
const props = defineProps<Props>();
const textList = ref([]);

watchEffect(() => {
  const { api, options, modelValue } = props;
  const values = Array.isArray(modelValue) ? modelValue : [modelValue];
  if (api) {
    const field = props.labelField || 'name';
    const params = { $soarQuery: { [`${props.valueField || 'id'}-in`]: values, fields: [field] }, queryType: 'list' };
    toAsyncLoader(api)(params).then((res) => {
      textList.value = res.list.map((x) => x[field]);
    });
  } else if (typeof options === 'string') {
    getDict(options).then((res) => {
      const m = {};
      for (const x of res) {
        m[x.value] = x.label;
      }
      textList.value = values.map((x) => m[x]);
    });
  } else if (options) {
    const m = {};
    for (const x of options) {
      m[x.value] = x.label;
    }
    textList.value = values.map((x) => m[x]);
  }
});
</script>
<script lang="ts">
export default {
  name: 'LgText',
};
</script>
